from app.common import jwt
from app.common.exception import errors
from app.database.db import async_db_session
from app.schemas.auth import AuthLoginSchema, AuthRegisterSchema
from app.crud.user import user_dao
from app.schemas.token import GetLoginToken


class UserService:
    @staticmethod
    async def login(*, obj: AuthLoginSchema):
        async with async_db_session.begin() as db:
            current_user = await user_dao.get_by_username(db, username=obj.username)
            if not current_user:
                raise errors.NotFoundError(msg="用户不存在")
            elif not await jwt.password_verify(
                f"{obj.password}{current_user.salt}", current_user.password
            ):
                raise errors.AuthorizationError(msg="密码错误")
            access_token, _ = await jwt.create_access_token(str(current_user.id))
            return GetLoginToken(
                access_token=access_token,
                user=current_user,  # type: ignore
            )

    @staticmethod
    async def register(*, obj: AuthRegisterSchema):
        async with async_db_session.begin() as db:
            if not obj.password:
                raise errors.ForbiddenError(msg="密码为空")
            username = await user_dao.get_by_username(db, username=obj.username)
            print("username", username)
            if username:
                raise errors.ForbiddenError(msg="用户已存在")
            return await user_dao.create(db, obj)


user_service: UserService = UserService()
